package com.hphs.controller;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hphs.info.ImgInfo;
import com.hphs.info.UploadInfo;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/upload")
public class UploadController {

    private static String filePath = "D:/software/nginx-1.29.2/html/";
    private static List<String> imgExts = CollUtil.newArrayList("jpg","png","jpeg","gif");

    @PostMapping
    public String upload(@RequestBody UploadInfo uploadInfo){
        String name =uploadInfo.getName();
        String base64=uploadInfo.getBase64();
        //切割正确的字符串 图片的base64编码
        String[] base64s= StrUtil.splitToArray(base64,"base64,");
        //转换字符数组
        byte[] bytes= Base64.decode(base64s[1]);
        name = IdUtil.getSnowflakeNextIdStr()+"_"+name;
        String ext = FileUtil.getSuffix(name);
        System.out.println(ext);
        String tempFolder = "image/";
        if (!imgExts.contains(ext)){
            tempFolder = ext + "/";
        }


        //        写入到nginx中
        FileUtil.writeBytes(bytes,filePath+tempFolder+name);
        return "http://www.hphs.com/"+tempFolder+name;
    }


    @GetMapping
    public List<ImgInfo> getimg(){
        //获得指定目录下所有的文件
        List<String> fileNames = FileUtil.listFileNames("D:/software/nginx-1.29.2/html/image");
        //使用stream进行元素转化
        List<ImgInfo> collect = fileNames.stream().map(item -> {
            return new ImgInfo(item, "http://www.hphs.com/image/" + item);
        }).collect(Collectors.toList());
        return collect;
    }

    @GetMapping("/video")
    public List<ImgInfo> getvideo(){
        //获得指定目录下所有的文件
        List<String> fileNames = FileUtil.listFileNames("D:/software/nginx-1.29.2/html/mp4");
        //使用stream进行元素转化
        List<ImgInfo> collect = fileNames.stream().map(item -> {
            return new ImgInfo(item, "http://www.hphs.com/mp4/" + item);
        }).collect(Collectors.toList());
        return collect;
    }
}
